package cn.kgc.javaweb.servlet;

import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 通过注解配置请求路径  servlet 3.0
 * /studentlist
 * @author mosin
 * date 2022/3/15
 * @version 1.0
 */
@WebServlet("/userlist")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("查询学生列表");
        //调用userService对象中的查询方法
        List<User> users = userService.findAll();

        //        转发和重定向

        //将users最终的查询结果传递到  userlist.jsp  -> servlet - >  service
        // ArrayList<User> users = new ArrayList<>();
        //
        // for (int i = 0; i < 5; i++) {
        //     users.add(User.builder().id(1).pwd("123456").uname("李四").role(1).build());
        // }

        //将学生信息的查询列表展示在前端页面
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        writer.write("<!DOCTYPE html>");
        writer.write("<html>");
        writer.write("<head>");
        writer.write("<meta charset=\"UTF-8\">");
        writer.write("</head>");
        writer.write("<body>");

        writer.write("<table border=\"1px\" width=\"100%\" height=\"200px\">");
        writer.write("<tr><th>id</th><th>用户名</th><th>密码</th><th>角色</th></tr>");

        //遍历集合 查看查询的结果
        users.forEach(user-> {
            writer.write("<tr><td>"+user.getId()+"</td><td>"+user.getUsername()+"</td><td>"+user.getPwd()+"</td><td>"+user.getRole()+"</td></tr>");
        });
        writer.write("</table>");
        writer.write("</body>");
        writer.write("</html>");

    }
}
